/*
 * Copyright 2012-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.context.properties.source;

import java.time.Duration;

import org.springframework.core.env.Environment;
import org.springframework.util.Assert;

/**
 * 可用于控制配置属性源缓存的接口。
 *
 * @author Phillip Webb
 * @since 2.3.0
 */
public interface ConfigurationPropertyCaching {

	/**
	 * 启用缓存，缓存时间无限制。
	 */
	void enable();

	/**
	 * 禁用缓存。
	 */
	void disable();

	/**
	 * 设置缓存中项目的存活时间。调用该方法也会启用缓存。
	 * @param timeToLive 存活时间
	 */
	void setTimeToLive(Duration timeToLive);

	/**
	 * 清除缓存，并在下次访问时强制重新加载。
	 */
	void clear();

	/**
	 * 获取环境中所有配置属性源的缓存控制实例。
	 * @param environment Spring 环境
	 * @return 控制该环境中所有源的缓存实例
	 */
	static ConfigurationPropertyCaching get(Environment environment) {
		return get(environment, null);
	}

	/**
	 * 获取某个环境中指定配置属性源的缓存实例。
	 * @param environment Spring 的环境对象
	 * @param underlyingSource 必须匹配的
	 * {@link ConfigurationPropertySource#getUnderlyingSource() 底层源}
	 * @return 控制匹配源的缓存实例
	 */
	static ConfigurationPropertyCaching get(Environment environment, Object underlyingSource) {
		Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
		return get(sources, underlyingSource);
	}

	/**
	 * 获取所有指定配置属性源的缓存实例。
	 * @param sources 配置属性源
	 * @return 控制这些源的缓存实例
	 */
	static ConfigurationPropertyCaching get(Iterable<ConfigurationPropertySource> sources) {
		return get(sources, null);
	}

	/**
	 * 获取指定配置属性源中匹配底层源的缓存实例。
	 * @param sources 配置属性源
	 * @param underlyingSource 必须匹配的
	 * {@link ConfigurationPropertySource#getUnderlyingSource() 底层源}
	 * @return 控制匹配源的缓存实例
	 */
	static ConfigurationPropertyCaching get(Iterable<ConfigurationPropertySource> sources, Object underlyingSource) {
		Assert.notNull(sources, "Sources must not be null");
		if (underlyingSource == null) {
			return new ConfigurationPropertySourcesCaching(sources);
		}
		for (ConfigurationPropertySource source : sources) {
			if (source.getUnderlyingSource() == underlyingSource) {
				ConfigurationPropertyCaching caching = CachingConfigurationPropertySource.find(source);
				if (caching != null) {
					return caching;
				}
			}
		}
		throw new IllegalStateException("Unable to find cache from configuration property sources");
	}

}
